import { useCallback, useEffect, useRef } from "react";

// 防抖
export function useDebounce<T extends (...args: never[]) => unknown>(
  fn: T,
  delay: number,
  immediate?: boolean
) {
  const fnRef = useRef(fn);
  const timerRef = useRef<number>();

  useEffect(() => {
    fnRef.current = fn;
  }, [fn]);

  return useCallback(
    (...args: Parameters<T>) => {
      immediate && !timerRef.current && fnRef.current(...args);
      clearTimeout(timerRef.current);
      timerRef.current = window.setTimeout(() => fnRef.current(...args), delay);
    },
    [delay]
  );
}

export function useThrottle<T extends (...args: never[]) => unknown>(
  fn: T,
  delay: number
) {
  const fnRef = useRef(fn);
  const clicked = useRef<boolean>(false);
  useEffect(() => {
    fnRef.current = fn;
  }, [fn]);

  return useCallback(
    (...args: Parameters<T>) => {
      if (clicked.current) return;
      clicked.current = true;
      setTimeout(() => {
        clicked.current = false;
      }, delay);
      fnRef.current(...args);
    },
    [delay]
  );
}
